/*
 * @Description:
 * @Author: zhihong deng
 * @Date: 2021-08-21 23:40:21
 * @LastEditors: zhihong deng
 * @LastEditTime: 2021-10-05 22:06:14
 */
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const log4js = require('./utils/log4j')
const router = require('koa-router')()
const util = require('./utils/util')
// const jwt = require('jsonwebtoken')
const koajwt = require('koa-jwt') // 验证token的插件
const users = require('./routes/users')
const menus = require('./routes/menus')
const roles = require('./routes/roles')
const depts = require('./routes/depts')
const leave = require('./routes/leave')

// error handler
onerror(app)

require('./config/db')

// middlewares
app.use(
	bodyparser({
		enableTypes: ['json', 'form', 'text'],
	})
)
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(
	views(__dirname + '/views', {
		extension: 'pug',
	})
)

app.use(async (ctx, next) => {
	await next()
	log4js.info('log output')
})

// logger
app.use(async (ctx, next) => {
	log4js.info(`get params:${JSON.stringify(ctx.request.query)}`)
	log4js.info(`post params:${JSON.stringify(ctx.request.body)}`)
	await next().catch((err) => {
		if (err.status == '401') {
			ctx.status = 200
			ctx.body = util.fail('Token认证失败', util.CODE.AUTH_ERROR)
		} else {
			throw err
		}
	})
})
// 过滤接口，有token才放行
app.use(
	koajwt({ secret: 'gino' }).unless({
		path: [/^\/api\/users\/login/],
	})
)

// routes
router.prefix('/api')

router.use(users.routes(), users.allowedMethods())
router.use(menus.routes(), menus.allowedMethods())
router.use(roles.routes(), roles.allowedMethods())
router.use(depts.routes(), depts.allowedMethods())
router.use(leave.routes(), leave.allowedMethods())

app.use(router.routes(), router.allowedMethods()) // 加载所有路由

// error-handling
app.on('error', (err, ctx) => {
	log4js.error(`${err.stack}`)
})

module.exports = app
